package myprotocol;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class SMPPProtocolDecoder implements ProtocolDecoder {
	private static final AttributeKey BUF_BYTE = new AttributeKey(
			SMPPProtocolDecoder.class, "bufb");

	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		try {
			IoBuffer bufTmp = null;
			byte[] buf = (byte[]) session.getAttribute(BUF_BYTE);
			if (buf == null) {
				// System.out.println("没有尚未处理的数据");
				bufTmp = in;
			} else {
				// System.out.println("合并尚未处理的数据");
				bufTmp = IoBuffer.allocate(buf.length + in.remaining());
				bufTmp.setAutoExpand(true);
				bufTmp.put(buf);
				bufTmp.put(in);
				bufTmp.flip();
			}
			while (bufTmp.remaining() >= 4
					&& bufTmp.remaining() >= bufTmp.getInt(bufTmp.position())) {// 循环处理数据包
//				int dataLen = bufTmp.getInt(bufTmp.position());
//				byte[] b = new byte[dataLen];
//				bufTmp.get(b);
//				SMPPPacket pak = null;
//				int id = -1;
//				id = SMPPIO.bytesToInt(b, 4, 4);
//				pak = PacketFactory.newInstance(id);
//				if (pak != null) {
//					pak.readFrom(b, 0);
//					out.write(pak);
//				}
			}
			if (bufTmp.hasRemaining()) {// 如果有剩余的数据，则放入Session中
				byte[] tmpb = new byte[bufTmp.remaining()];
				bufTmp.get(tmpb);
				session.setAttribute(BUF_BYTE, tmpb);
			}
		}

		catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void dispose(IoSession session) throws Exception {

	}

	public void finishDecode(IoSession session, ProtocolDecoderOutput out)
			throws Exception {
	}

}